package utils

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var (
	timeRegex = []*regexp.Regexp{
		regexp.MustCompile(`([\d]{4})-([\d]{1,2})-([\d]{1,2})\s*([\d]{1,2}:[\d]{1,2})?`),
		regexp.MustCompile(`([\d]{4}).([\d]{1,2}).([\d]{1,2})\s*([\d]{1,2}:[\d]{1,2})?`),
		regexp.MustCompile(`([\d]{4})/([\d]{1,2})/([\d]{1,2})\s*([\d]{1,2}:[\d]{1,2})?`),
		regexp.MustCompile(`([\d]{4})年([\d]{1,2})月([\d]{1,2})日\s*([\d]{1,2}:[\d]{1,2})?`),
	}
)

func GetTime(str string) int64 {
	for _, t := range timeRegex {
		ts := t.FindStringSubmatch(str)
		if len(ts) < 4 {
			continue
		}
		var h string = "00:00"
		if len(ts) > 4 && ts[4] != "" {
			h = ts[4]
		}

		year, _ := strconv.Atoi(ts[1])
		month, _ := strconv.Atoi(ts[2])
		day, _ := strconv.Atoi(ts[3])

		timeAt := strings.Split(h, ":")
		hour, _ := strconv.Atoi(timeAt[0])
		var minute int
		if len(timeAt) > 1 {
			minute, _ = strconv.Atoi(timeAt[1])
		}

		v := fmt.Sprintf("%04d%02d%02d %02d:%02d", year, month, day, hour, minute)
		tm, err := time.Parse("20060102 15:04", v)
		if err == nil {
			return tm.Unix()
		}
	}
	return 0
}

func CurrentMills() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}
